<?php

namespace App\Http\Controllers\Admin;

use App\Events\UserEvent;
use App\Http\Controllers\Controller;
use App\Models\UserGroup;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->middleware('guest')->except('logout');
        $redirect = $request->input('redirect');
        if ($redirect) {
            $this->redirectTo = $redirect;
        }
    }

    public function redirectTo()
    {
        return admin_url('');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function index(){

        return $this->view('admin.login');
    }

    public function validateLogin(Request $request)
    {
        $this->validate($request, [
            'account' => 'bail|required|string|account',
            'password' => 'bail|required|string|password'
        ]);
    }

    public function authenticated(Request $request, $user)
    {
        $group = UserGroup::find($user->admingid);
        if ($group){
            $privileges = unserialize($group->privileges);
            if (!is_array($privileges)) $privileges = [];
        } else {
            $privileges = [];
        }
        session()->put('adminprivileges', $privileges);
        event(new UserEvent($user, 'login'));
    }

    public function attemptLogin(Request $request)
    {
        $account  = $request->input('account');
        $password = $request->input('password');

        $emailLogin = $this->guard()->attempt([
            'email'=>$account,
            'password'=>$password,
            'admincp'=>1
        ], false);

        if ($emailLogin) {
            $request->session()->put('adminid', Auth::id());
            return true;
        }

        $mobileLogin = $this->guard()->attempt([
            'mobile'=>$account,
            'password'=>$password,
            'admincp'=>1
        ], false);

        if ($mobileLogin) {
            $request->session()->put('adminid', Auth::id());
            return true;
        }

        return false;
    }

    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        $redirect = $request->input('redirect');
        if ($redirect) {
            return redirect($redirect);
        } else {
            return redirect(admin_url('login'));
        }
    }

    public function username()
    {
        return 'account';
    }
}
